<template>
  <div class="page_padding">
    <MyNavBar class="nav" @goback="goback" :title="Pagetitle"></MyNavBar>
    <StatisticTab :statisticInfo="statisticInfo">
      <div slot="btn" class="btn-box">
        <div
          v-if="statisticInfo.numNoSub > 0"
          class="urge"
          :class="{ inform: statisticInfo.isUrgeAll !== '0', no_nform: statisticInfo.isUrgeAll === '0' }"
          @click="urgeSub('2')">
          {{ statisticInfo.isUrgeAll === '0' ? '已催报' : '全部催报' }}
        </div>
        <div v-else class="subbmit_btn" @click="subbmitAll">提交结果</div>
      </div>
      <div class="tips" slot="tips" v-if="assessMode === 1">
        温馨提示：本季度可评全优等次{{ goodNum }}人, 已评{{ chooseGoodNum }}人
      </div>
      <div class="tips" slot="tips" v-else>温馨提示：本季度可评“好”等次{{ goodNum }}人, 已评{{ chooseGoodNum }}人</div>
    </StatisticTab>
    <UserTab :roll-list="userList" :user-list="userList" @deal-data="InfoTitTab" ref="userTab"></UserTab>
    <div class="tab-con" :class="{ big: statusValue == 1 || statusValue == 2 }">
      <div class="score_cont" v-if="statusValue != 0 && scoreContentFlag">
        <!-- v-if="statusValue != 0 && scoreContentFlag" -->
        <ScoreType
          ref="scoreType"
          :scoreListDetail="scoreListData || {}"
          :busSign="busSign"
          :userInfo="activeUserInfo"
          :otherList="otherLists"
          :goodNum="goodNum"
          :quarterNow="quarterNow"
          :groupByLeader="groupByLeader"
          :chooseGoodNum="chooseGoodNum"
          :disabled="groupByLeader && activeUserInfo.leaderAssessScore && activeUserInfo.leaderAssessScore < 100"
          :calcRule="calcRule"
          :needPlusMinusPoints="needPlusMinusPoints"
          :needPeopleAssess="needPeopleAssess"
          :showHistory="showHistory"
          @renew-data="renewData"
          :assessMode="assessMode" />
      </div>
      <van-empty description="暂无数据" v-else />
    </div>

    <div class="fead_boot" v-if="statusValue != 0">
      <div class="btn_li" @click="postMark()">保存</div>
    </div>
    <div class="fead_boot" v-else>
      <div class="btn_li" @click="urgeSub('1')" :style="isUrgeValue === '0' ? 'background: #D7D7D7;' : ''">
        <span v-if="isUrgeValue === '0'">已催报</span>
        <span v-else>催报</span>
      </div>
    </div>

    <van-dialog
      v-model="subbmitShow"
      title="提醒"
      show-cancel-button
      @confirm="onSubbmit"
      @cancle="subbmitShow = 'false'"
      get-container="#app">
      <div class="message">{{ tipMessage }}</div>
      <OtherTable :otherList="otherLists" :chooseGoodNum="chooseGoodNum" :assessMode="assessMode"></OtherTable>
    </van-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import MyNavBar from '@com/MyNavBar'
import BoardSound from '@com/BoardSound'
import ScoreType from './components/ScoreType'
import OtherTable from './components/OtherTable'
import StatisticTab from './components/StatisticTab.vue'
import UserTab from './components/UserTab.vue'
import {
  getFirstAssessData,
  getAssessContent,
  submitAllAssess,
  getUserAssessData,
  saveSimpleAssess,
  getCheckSubmitAllAssess,
  saveAssessScore,
} from '@api/api-comment.js'
import { saveUrgeByNeedDeal } from '@api/api-documentary.js'
export default {
  name: 'ScoreNews',
  components: {
    MyNavBar,
    ScoreType,
    BoardSound,
    OtherTable,
    StatisticTab,
    UserTab,
  },
  props: {},
  data() {
    return {
      recordType: '', //01-02 月度 01-03 季度
      Pagetitle: '季度评价',
      infoData: {
        userName: '',
        orgName: ' ',
        title: '',
      },
      scoringId: '',
      // 打分类型
      busSign: '',
      recordReplyShow: false,
      statisticInfo: {
        numAll: 0, // 总人数
        numNo: 0, // 未评
        numHas: 0, // 已评
        numNoSub: 0, // 未提交
        isUrgeAll: '', // 是否催报
      },
      isUrgeValue: '0', // 是否催报
      activePeo: 0,
      requestType: '', //请求用户类型 1表示已评议
      subbmitShow: false,
      targetData: [],
      scoreData: [],
      statusValue: '',
      scoreList: {}, //打分列表
      scoreListData: {},
      userList: [],
      tipMessage: '',
      activePeoIndex: 0,
      otherList: [],
      otherLists: [],
      subbmitSatus: 0,
      scoreContentFlag: false,
      isCommit: false,
      goodNum: 0,
      chooseGoodNum: 0,
      activeRank: '',
      isSave: false,
      groupByLeader: false, // 是否按领导分组展示信息
      quarterNow: 0,
      activeUserInfo: {},
      calcRule: [],
      needPlusMinusPoints: true, // 是否显示加分项
      needPeopleAssess: true, // 是否显示民主测评
      showHistory: false, // 是否显示历史评价
      assessMode: 2, //  1 指标 2综合
    }
  },
  computed: {
    ...mapGetters(['activeEvaluation']),
  },
  created() {},
  mounted() {
    this.userList = this.activeEvaluation
    this.Pagetitle = this.$route.query.needDealName
    this.recordType = this.$route.query.recordType
    this.busSign = this.$route.query.busSign
    this.requestType = this.$route.query.requestType || 0
    this.dealData(Number(this.$route.query.activePeoIndex), '0')
    this.setTopNum()
  },
  watch: {
    scoreList: {
      handler(news) {
        this.scoreListData = news
      },
      deep: true,
    },
    activeEvaluation: {
      handler(news) {
        this.userList = news
        // const arr = news.filter(item => {
        //   return item.assessRank === '1' || item.mainLeaderAssessRank === '1'
        // })
        // this.chooseGoodNum = arr.length
        this.setTopNum()
      },
      deep: true,
      immediate: true,
    },
    otherList: {
      handler(news) {
        const arr = news.filter(item => {
          return item.assessRank === '1' || (!item.assessRank && item.mainLeaderAssessRank === '1')
        })
        this.chooseGoodNum = arr.length
        this.otherLists = news
      },
      deep: true,
    },
    Pagetitle: {
      handler(news) {
        if (news.indexOf('第一季度') !== -1) {
          this.quarterNow = 0
        } else if (news.indexOf('第二季度') !== -1) {
          this.quarterNow = 1
        } else if (news.indexOf('第三季度') !== -1) {
          this.quarterNow = 2
        } else if (news.indexOf('第四季度') !== -1) {
          this.quarterNow = 3
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 判断数据是否已经填写完
    postMark() {
      this.$refs.scoreType.reviewData()
    },
    goback() {
      this.$store.state.alive = false
      this.$router.go(-1)
    },
    getPageGradeDataList(type) {
      if (this.busSign.includes('DEAL_LEADER_ASSESS')) {
        this.getFirstAssessData(type)
      } else {
        this.getUserAssessData(type)
      }
    },
    FinishCondition(status) {
      if (status == '1') {
        return 'color:#EE0A24'
      } else if (status == '2' || status == '3') {
        return 'color:#67C23A'
      }
    },
    InfoTitTab({ item, index }) {
      if (item.userId === this.activePeo) return
      if (!this.isSave && this.userList[this.activePeoIndex].assessRank) {
        this.$set(this.userList[this.activePeoIndex], 'assessRank', this.activeRank)
      }
      this.getPageGradeDataList()
      this.isSave = false
      this.scoreContentFlag = false
      this.scoreList = {}
      this.dealData(index, '1')
      this.activeRank = this.userList[index].assessRank
    },
    subbmitAll() {
      if (this.statisticInfo.numAll !== this.statisticInfo.numHas) {
        this.tipMessage = `还有${this.statisticInfo.numAll - this.statisticInfo.numHas}人未评价，请完成评价后再提交结果`
      } else {
        getCheckSubmitAllAssess({
          isCheckGood: 1,
          needId: this.$route.query.needId,
        }).then(res => {
          if (res.status === 200) {
            this.subbmitSatus = res.data.status
            if (res.data.status == 0) {
              this.tipMessage = '您确定要提交所有评分吗？'
            } else {
              this.tipMessage = res.data.tips
            }
          }
        })
      }
      this.subbmitShow = true
    },
    onSubbmit() {
      if (this.subbmitSatus == 2 || this.statisticInfo.numAll !== this.statisticInfo.numHas) {
        this.subbmitShow = false
      } else {
        submitAllAssess({ needId: this.$route.query.needId, isCheckGood: 0 }).then(res => {
          if (res.status === 200) {
            this.$toast.success('提交结果成功')
            setTimeout(() => {
              this.isCommit = true
              this.$store.state.stateAlive = false
              this.$router.go(-2)
            }, 500)
          }
        })
      }
    },
    // 打分详情
    getAssessContent() {
      getAssessContent({
        busSign: this.busSign,
        noteId: this.noteId,
        needId: this.$route.query.needId,
      }).then(res => {
        const data = res.data
        this.scoreList = data
        this.userList[this.activePeoIndex].extraData.entryCont =
          (data.scoringExpressionVO && data.scoringExpressionVO.expression) || ''
        this.userList[this.activePeoIndex].extraData.audioList =
          (data.scoringExpressionVO && data.scoringExpressionVO.voiceList) || []
        this.userList[this.activePeoIndex].reviewsaData.entryCont =
          (data.scoringSuggestVO && data.scoringSuggestVO.suggestion) || ''
        this.userList[this.activePeoIndex].reviewsaData.audioList =
          (data.scoringSuggestVO && data.scoringSuggestVO.voiceList) || []
        this.userList[this.activePeoIndex].remark = data.remark || ''
        this.activeUserInfo = this.userList[this.activePeoIndex]
        this.$store.commit('setActiveEvaluation', this.userList)
        this.scoreContentFlag = true
      })
    },
    getFirstAssessData(type) {
      getFirstAssessData({
        needId: this.$route.query.needId,
        recordType: this.recordType,
        saScoringId: this.scoringId || this.$route.query.saScoringId,
        busSign: this.busSign,
        requestType: this.requestType,
        keyWord: '',
        title: this.$route.query.title || '',
      }).then(res => {
        if (type === 'urge') {
          this.statisticInfo.isUrgeAll = res.data.isUrge
          return
        }
        this.assessMode = res.data.assessMode || 2
        this.needPlusMinusPoints = res.data.needPlusMinusPoints
        this.needPeopleAssess = res.data.needPeopleAssess
        this.showHistory = res.data.showHistory
        this.otherList = res.data.userStatusVOList
        this.statisticInfo.isUrgeAll = res.data.isUrge
        this.goodNum = res.data.goodRankCount
        this.dealUserDataList(this.otherList)
      })
    },
    getUserAssessData(type) {
      getUserAssessData({
        needId: this.$route.query.needId,
      }).then(res => {
        this.calcRule = res.data.calcRule
        this.needPlusMinusPoints = res.data.needPlusMinusPoints
        this.needPeopleAssess = res.data.needPeopleAssess
        this.showHistory = res.data.showHistory
        this.Pagetitle = res.data.title
        this.statisticInfo.isUrgeAll = res.data.isUrge
        this.goodNum = res.data.goodRankCount
        // 是否按分组领导展示
        this.groupByLeader = res.data.isGroupByLeader === 1 ? true : false
        if (this.groupByLeader) {
          this.groupLeaderDeal(res.data)
          return
        }
        // 正常展示
        let arr = [...res.data.userAssessDataResponseVOS, ...res.data.leaderAssessDataResponseVOS]
        this.otherList = arr
        this.dealUserDataList(this.otherList, res.data.isSetLeaderAssess)
      })
    },
    postMark1() {
      let extraData = this.userList[this.activePeoIndex].extraData,
        reviewsaData = this.userList[this.activePeoIndex].reviewsaData,
        totalScore = this.userList[this.activePeoIndex].totalScore,
        rank = this.userList[this.activePeoIndex].assessRank || this.userList[this.activePeoIndex].mainLeaderAssessRank,
        remark = this.userList[this.activePeoIndex].remark

      if (!rank) {
        this.$dialog
          .alert({
            title: '提示',
            message: '请选择考核结果等次',
          })
          .then(() => {
            // on close
          })
        return
      }
      if (rank == 3 && !reviewsaData.entryCont) {
        this.$dialog
          .alert({
            title: '提示',
            message: '根据评价规则，等次为“一般”，需要填写说明',
          })
          .then(() => {
            // on close
          })
        return
      }
      if (rank == 4 && !remark) {
        this.$dialog
          .alert({
            title: '提示',
            message: '等次为“较差”，需要填写备注说明',
          })
          .then(() => {
            // on close
          })
        return
      }
      saveSimpleAssess([
        {
          assessRank: rank || '',
          saveStatus: '1',
          scoringId: this.scoringId,
          processInstanceId: this.$route.query.processInstanceId || '',
          taskId: this.$route.query.taskId || '',
          totalScore: totalScore,
          scoringSuggestVO: {
            suggestion: reviewsaData.entryCont,
            voiceList: reviewsaData.audioList,
          },
          scoringExpressionVO: {
            expression: extraData.entryCont,
            voiceList: extraData.audioList,
          },
          remark: remark || '',
        },
      ]).then(res => {
        if (res.status == 200) {
          if (res.data.status === 0) {
            this.isSave = true
            this.$toast.success('保存成功')
            this.userList[this.activePeoIndex].status = 2
            this.$store.commit('setActiveEvaluation', this.userList)
            this.otherList = this.userList
            this.getPageGradeDataList('1')
          } else {
            this.$toast.fail(res.data.tips)
          }
        }
      })
    },
    // 催报
    urgeSub(type) {
      let that = this
      if (type === '2' && that.statisticInfo.isUrgeAll === '0') {
        return
      } else if (type === '1' && that.isUrgeValue === '0') {
        return
      }
      that.goUrge(type)
    },
    // 催报
    goUrge(type) {
      let that = this
      let message = '您确定要进行催报吗？'
      if (type === 2) {
        let arrUN = this.otherList.filter(item => {
          return item.status == 0
        })
        if (arrUN.length > 0) {
          let arr = []
          arrUN.forEach(item => {
            arr.push(item.userName)
          })
          message = `本季度个人工作汇总未完成人员 ${arr.join('、')}，您确定要进行催报吗？`
        }
      }
      that.$dialog
        .confirm({
          title: '提示',
          message: message,
        })
        .then(() => {
          saveUrgeByNeedDeal({
            needId: this.$route.query.needId,
            type: Number(type),
            urgeUserId: that.activePeo,
            optionUserId: localStorage.userId,
            tenantId: localStorage.tenantId,
          })
            .then(res => {
              if (res.status === 200) {
                if (type == 1) {
                  this.isUrgeValue = '0'
                  this.$refs.userTab.changeUserUrge(this.activePeo)
                  that.getPageGradeDataList('urge')
                } else {
                  this.statisticInfo.isUrgeAll = '0'
                  this.isUrgeValue = '0'
                }
              }
            })
            .catch(err => {})
        })
        .catch(() => {
          // on cancel
        })
    },
    setTopNum() {
      let [total, noScoreNum, scoredNum, noSubmitNum] = [0, 0, 0, 0]
      this.userList.forEach(item => {
        total++
        if (item.status === 1) {
          noScoreNum++
        } else if (item.status === 2 || item.status === 3) {
          scoredNum++
        } else if (item.status === 0) {
          noSubmitNum++
        }
      })

      this.statisticInfo.numAll = total
      this.statisticInfo.numNo = noScoreNum
      this.statisticInfo.numHas = scoredNum
      this.statisticInfo.numNoSub = noSubmitNum
    },
    dealUserDataList(list, isSetLeaderAssess) {
      list.forEach(item => {
        item.extraData = {
          id: '',
          title: '',
          entryCont: '',
          audioList: [],
        }
        item.reviewsaData = {
          id: '',
          title: '',
          entryCont: '',
          audioList: [],
        }
        item.scoringRadio = ''
        item.isSetLeaderAssess = isSetLeaderAssess
      })
      if (isSetLeaderAssess === 1) {
        list.forEach(item => {
          if (!item.mainLeaderAssessRank && item.leaderAssessRank) {
            item.mainLeaderAssessRank = item.leaderAssessRank
            item.mainLeaderAssessScore = item.leaderAssessScore
          }
        })
      }
      this.$store.commit('setActiveEvaluation', list)
    },
    groupLeaderDeal(data) {
      let rollList = []
      let userListArr = data.leaderGroupUserAssessVOS || []
      userListArr.forEach(item => {
        item.userAssessDataResponseVOS.forEach(li => {
          li.extraData = {
            id: '',
            title: '',
            entryCont: '',
            audioList: [],
          }
          li.reviewsaData = {
            id: '',
            title: '',
            entryCont: '',
            audioList: [],
          }
          li.scoringRadio = ''
          li.isSetLeaderAssess = data.isSetLeaderAssess
          if (data.isSetLeaderAssess === 1) {
            if (!li.mainLeaderAssessRank && li.leaderAssessRank) {
              li.mainLeaderAssessRank = li.leaderAssessRank
              li.mainLeaderAssessScore = li.leaderAssessScore
            }
          }
          li.leaderId = item.leaderId
          li.leaderName = item.leaderName
        })
        rollList.push(...item.userAssessDataResponseVOS)
      })
      this.otherList = rollList
      this.userList = rollList
    },
    renewData(data) {
      if (this.assessMode === 1) {
        this.saveAssessScore(data)
      } else {
        this.userList[this.activePeoIndex] = data
        this.postMark1()
      }
    },
    saveAssessScore(param) {
      saveAssessScore(param).then(res => {
        if (res.status === 200) {
          const data = res.data
          if (data.status === 0) {
            this.isSave = true
            this.$toast.success('保存成功')
            this.userList[this.activePeoIndex].status = 2
            if (param.flag) {
              this.userList[this.activePeoIndex].assessRank = '1'
            } else {
              this.userList[this.activePeoIndex].assessRank = ''
            }
            this.otherList = this.userList
            setTimeout(() => {
              this.getPageGradeDataList('1')
            }, 500)
          } else {
            this.$toast.fail(data.tips)
          }
        }
      })
    },
    dealData(i, type) {
      this.$refs.userTab.changeUser(this.userList[i].userId)
      this.activePeoIndex = i
      this.userId = this.userList[i].userId
      this.activePeo = this.userList[i].userId
      this.scoringId = this.userList[i].saScoringId
      this.processInstanceId = this.userList[i].processInstanceId
      this.taskId = this.userList[i].taskId
      this.noteId = this.userList[i].noteId
      this.statusValue = this.userList[i].status
      this.isUrgeValue = this.userList[i].isUrge || '0'
      this.getPageGradeDataList(type)
      if (this.statusValue === 2) {
        this.getAssessContent()
      } else {
        this.activeUserInfo = this.userList[i]
        this.scoreContentFlag = true
      }
    },
  },
  destroyed() {
    if (!this.isCommit) {
      let data = {
        activePeo: this.activePeo,
        activePeoIndex: this.activePeoIndex,
      }
      sessionStorage.setItem('activeInfo', JSON.stringify(data))
    }
  },
}
</script>

<style lang="scss" scoped>
.page_padding {
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .cont-tab::-webkit-scrollbar {
    display: none;
  }
  /deep/ .van-overlay {
    position: fixed;
  }
  .tab-con {
    position: relative;
    flex: 1;
    overflow: hidden;
    margin: 10px 16px;
    .score_cont {
      height: 100%;
      background: #ffffff;
      border-radius: 5px;
      padding-bottom: 10px;
    }
  }
  .big {
    padding-bottom: 60px;
  }
  /deep/.van-dialog__content {
    padding: 8px 0;
  }
}
.message {
  padding: 0 15px;
  margin-bottom: 10px;
  text-align: center;
}
</style>
